package leetcode_题库;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/23 10:21 星期二
 */
public class _617_合并二叉树 {
    public static void main(String[] args) {
        TreeNode root1 = new TreeNode(1);
        TreeNode root1S1 = new TreeNode(3);
        TreeNode root1S2 = new TreeNode(2);
        TreeNode root1S3 = new TreeNode(5);
        root1.left = root1S1;
        root1.right = root1S2;
        root1S1.left = root1S3;

        TreeNode root2 = new TreeNode(2);
        TreeNode root2S1 = new TreeNode(1);
        TreeNode root2S2 = new TreeNode(3);
        TreeNode root2S3 = new TreeNode(4);
        TreeNode root2S4 = new TreeNode(7);
        root2.left = root2S1;
        root2.right = root2S2;
        root2S1.right = root2S3;
        root2S2.right = root2S4;

        mergeTrees(root1, root2);
    }

    public static TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null){
            //如果这俩结点都是null，没必要继续，返回空结点
            return null;
        }

        if (root1 != null && root2 != null) {
            //二者都不为null，我们相加
            root1.val = root1.val + root2.val;
        }else if (root1 ==null){
            //root1是null，root2不是，赋值
            root1 = new TreeNode(root2.val);
        }
        //左右深优
        root1.left = mergeTrees(root1.left,root2 == null? null : root2.left);
        root1.right = mergeTrees(root1.right,root2 == null? null : root2.right);
        //返回root1
        return root1;
        /*
            > 2022/08/23 10:51:05
            解答成功:
                执行耗时:0 ms,击败了100.00% 的Java用户
                内存消耗:41.1 MB,击败了96.54% 的Java用户
         */
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
